const fs = require('fs-extra');
const path = require('path');
const { minify: minifyHTML } = require('html-minifier');
const UglifyJS = require('uglify-js');
const CleanCSS = require('clean-css');

// 清理并创建dist目录
const distDir = path.join(__dirname, 'dist');
fs.removeSync(distDir);
fs.ensureDirSync(distDir);

console.log('开始构建...');

// 读取源文件
const htmlContent = fs.readFileSync('index.html', 'utf8');
const cssContent = fs.readFileSync('style.css', 'utf8');
const jsContent = fs.readFileSync('script.js', 'utf8');

// 压缩CSS
console.log('压缩CSS文件...');
const cleanCSS = new CleanCSS({
  level: 2,
  returnPromise: false
});
const minifiedCSS = cleanCSS.minify(cssContent);

if (minifiedCSS.errors.length > 0) {
  console.error('CSS压缩错误:', minifiedCSS.errors);
  process.exit(1);
}

fs.writeFileSync(path.join(distDir, 'style.min.css'), minifiedCSS.styles);
console.log('CSS压缩完成');

// 压缩JavaScript
console.log('压缩JavaScript文件...');
const minifiedJS = UglifyJS.minify(jsContent, {
  compress: {
    drop_console: false,
    drop_debugger: true
  },
  mangle: true
});

if (minifiedJS.error) {
  console.error('JavaScript压缩错误:', minifiedJS.error);
  process.exit(1);
}

fs.writeFileSync(path.join(distDir, 'script.min.js'), minifiedJS.code);
console.log('JavaScript压缩完成');

// 处理HTML文件，更新资源引用
console.log('处理HTML文件...');
let processedHTML = htmlContent
  .replace('href="style.css"', 'href="style.min.css"')
  .replace('src="script.js"', 'src="script.min.js"');

// 压缩HTML
const minifiedHTML = minifyHTML(processedHTML, {
  removeComments: true,
  removeRedundantAttributes: true,
  removeScriptTypeAttributes: true,
  removeStyleLinkTypeAttributes: true,
  sortClassName: true,
  useShortDoctype: true,
  collapseWhitespace: true,
  conservativeCollapse: true,
  preserveLineBreaks: false,
  minifyCSS: true,
  minifyJS: true
});

fs.writeFileSync(path.join(distDir, 'index.html'), minifiedHTML);
console.log('HTML处理完成');

// 复制LICENSE文件
if (fs.existsSync('LICENSE')) {
  fs.copyFileSync('LICENSE', path.join(distDir, 'LICENSE'));
  console.log('LICENSE文件已复制');
}

// 生成构建信息
const buildInfo = {
  buildTime: new Date().toISOString(),
  version: require('./package.json').version,
  files: {
    'index.html': fs.statSync(path.join(distDir, 'index.html')).size,
    'style.min.css': fs.statSync(path.join(distDir, 'style.min.css')).size,
    'script.min.js': fs.statSync(path.join(distDir, 'script.min.js')).size
  }
};

fs.writeFileSync(path.join(distDir, 'build-info.json'), JSON.stringify(buildInfo, null, 2));

console.log('\n构建完成！');
console.log('输出目录:', distDir);
console.log('文件大小:');
console.log(`  index.html: ${(buildInfo.files['index.html'] / 1024).toFixed(2)} KB`);
console.log(`  style.min.css: ${(buildInfo.files['style.min.css'] / 1024).toFixed(2)} KB`);
console.log(`  script.min.js: ${(buildInfo.files['script.min.js'] / 1024).toFixed(2)} KB`);

const originalSizes = {
  html: fs.statSync('index.html').size,
  css: fs.statSync('style.css').size,
  js: fs.statSync('script.js').size
};

const totalOriginal = originalSizes.html + originalSizes.css + originalSizes.js;
const totalMinified = buildInfo.files['index.html'] + buildInfo.files['style.min.css'] + buildInfo.files['script.min.js'];
const compressionRatio = ((totalOriginal - totalMinified) / totalOriginal * 100).toFixed(2);

console.log(`\n压缩率: ${compressionRatio}% (${(totalOriginal / 1024).toFixed(2)} KB → ${(totalMinified / 1024).toFixed(2)} KB)`);
console.log('\n可以直接部署dist目录中的文件！');